package sg.edu.nus.iss.phoenix.authenticate.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import sg.edu.nus.iss.phoenix.authenticate.dao.RoleDao;
import sg.edu.nus.iss.phoenix.authenticate.dao.UserDao;
import sg.edu.nus.iss.phoenix.authenticate.dao.impl.RoleDaoImpl;
import sg.edu.nus.iss.phoenix.authenticate.entity.Role;
import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.core.dao.DAOFactoryImpl;
import sg.edu.nus.iss.phoenix.core.exceptions.NotFoundException;

/**
 * UserService Class provides the Access to User DAO
 * @author Swami Nathan Antony Swami(A0092692W)
 * @version 1.0 2012/9/20
*/ 
public class UserService {
	DAOFactoryImpl factory;
	UserDao udao;
	RoleDao rdao;

	public UserService() {
		super();
		factory = new DAOFactoryImpl();
		udao = factory.getUserDAO();
		rdao = factory.getRoleDAO();

	}

	public void insertUser(User user) {
		try {
			udao.create(user);
			//// System.out.println("user created " + user);
			for (Role role : user.getRoles()) {
				try {
					rdao.createUserRole(user, role);
				} catch (NotFoundException e) {
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void updateUser(User user) {
		try {
			udao.save(user);
			List<Role> newRoles = rdao.getUserRole(user);
			//delete existing roles and create roles again
			rdao.deleteUserRoles(user);		
			for (Role role : user.getRoles()) {
				try {
					rdao = new RoleDaoImpl();
					rdao.createUserRole(user, role);
				} catch (NotFoundException e) {
					e.printStackTrace();
				}
			}
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void deleteUser(User user) {
		try {
			udao.delete(user);
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public List<User> findAllUsers() {
		List<User> currentList = new ArrayList<User>();

		try {
			currentList = udao.loadAll();
			for (User user : currentList) {
				try {
					factory = new DAOFactoryImpl();
					rdao = factory.getRoleDAO();
					user.setRoles(rdao.getUserRole(user));
				} catch (NotFoundException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return currentList;

	}

	public User loadUser(User user2) {		
		try {
			udao = factory.getUserDAO();
			user2 = udao.load(user2);
			factory = new DAOFactoryImpl();
			rdao = factory.getRoleDAO();
			user2.setRoles(rdao.getUserRole(user2));
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user2;			
	}
}
